package com.cdyZuul.ZuulFilter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import entity.IpUtil;
import entity.IpRuleChecker;
import com.cdyZuul.tool.RouteLocatorUtil;
import com.netflix.zuul.exception.ZuulException;
import entity.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Set;



/**
 * ip黑名单过滤器。当开启了EnableBlackList时才启用
 *
 */
@Component
public class BlackListFilter extends ZuulFilter {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private IpRuleChecker ipRuleChecker;
    @Resource
    private RouteLocator routeLocator;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        //让该filter位置靠前
      return   FilterConstants.PRE_DECORATION_FILTER_ORDER - 5;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        if (ipRuleChecker == null) {
            return null;
        }

        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest serverHttpRequest = ctx.getRequest();
        String userIp = IpUtil.getIpAddress(serverHttpRequest);
        boolean isBlack = ipRuleChecker.check(userIp);

        if (isBlack) {
            //解析出请求的app名字
            String appName = RouteLocatorUtil.parseAppNameAndPath(routeLocator, serverHttpRequest)[0];
            //这些被排除的APP，黑名单也允许访问
            Set<String> exceptApps = ipRuleChecker.exceptApps();
            if (!CollectionUtils.isEmpty(exceptApps) && exceptApps.contains(appName)) {
                return null;
            } else {
                throw  new  ZuulException("权限不足", StatusCode.ACCESSERROR,"此ip被加入黑名单:"+userIp);
            }
        }

        return null;
    }

}
